<?php

require_once('Vega/Dao/Table.php');
require_once('Mobitv/Commons/Functions.php');

class Mobitv_Admin_UploadDao extends Vega_Dao_Table {

    const MASTER	= 'master';

    public function saveUploadQueue($uploadId, $memberId)
    {
        $uploadId = $this->_db->valueQuote($uploadId);
        $memberId = intval($memberId);
        $sql = "INSERT INTO upload_queue SET id=$uploadId, member_id=$memberId, started_time=NOW() ON DUPLICATE KEY UPDATE updated_time=NOW()";
        $this->_db->queryWrite($sql);
    }

    public function updateUploadQueue($uploadId, $filename)
    {
        $uploadId = $this->_db->valueQuote($uploadId);
        $filename = $this->_db->valueQuote($filename);
        $sql = "INSERT INTO upload_queue SET id=$uploadId, file_src=$filename, started_time=NOW() ON DUPLICATE KEY UPDATE file_src=$filename, updated_time=NOW()";
        $this->_db->queryWrite($sql);
    }

    public function updateInfo($uploadId, $data) {
        $uploadId       = $this->_db->valueQuote($uploadId);
        $title          = $this->_db->valueQuote($data['title']);
        $description    = $this->_db->valueQuote($data['description']);
        $tag            = $this->_db->valueQuote($data['tag']);
        $categoryId     = $this->_db->valueQuote($data['category_id']);
        $source         = $this->_db->valueQuote($data['source']);
        $price          = intval($data['price']);
        $downloadPrice  = intval($data['download_price']);
        $subCpId        = intval($data['subcp_id']);
        $hd             = intval($data['hd']);
        $qos            = intval($data['qos']);

        $sql = "UPDATE upload_queue SET title=$title, description=$description, tag=$tag, hd=$hd, qos=$qos, category_id=$categoryId, subcp_id=$subCpId, price=$price, download_price=$downloadPrice, source=$source, updated_time=NOW() WHERE id=$uploadId";
        try {
                $this->_db->queryWrite($sql);
        } catch (Exception $e) {
                return false;
        }

        // update success
        return true;
    }

    public function saveUploadedClip($uploadId) {
        $uploadId = $this->_db->valueQuote($uploadId);

        $sql = "SELECT * FROM upload_queue WHERE id=$uploadId";
        $this->_db->query($sql, self::MASTER);
        if(!$data = $this->_db->fetchRow()) return false;

        $sql = "SELECT msID AS id FROM movie_server WHERE deleted=0 AND actived=1";
        $this->_db->query($sql, self::MASTER);
        if(!$server = $this->_db->fetchRow()) return false;

        $title = $this->_db->valueQuote($data['title']);
        $titleVn = $this->_db->valueQuote(stripText($data['title']));
        $description = $this->_db->valueQuote($data['description']);
        $descriptionVn = $this->_db->valueQuote(stripText($data['description']));
        $tag = $this->_db->valueQuote($data['tag']);
        $source = $this->_db->valueQuote($data['source']);
        $price = intval($data['price']);
        $downloadPrice = intval($data['download_price']);
        $categoryId = intval($data['category_id']);
        $memberId = intval($data['member_id']);
        $subCpId = intval($data['subcp_id']);
        $msId = intval($server['id']);
        $hd = intval($data['hd']);

        $sql = "INSERT INTO clip SET upload_id=$uploadId, ms_id=$msId, title=$title, title_vn=$titleVn, description=$description, description_vn=$descriptionVn, tag=$tag, hd=$hd, price=$price, download_price=$downloadPrice, category_id=$categoryId, member_id=$memberId, subcp_id=$subCpId, source=$source, created_time=now()";
        $this->_db->queryWrite($sql);

        // get clip info
        $sql = "SELECT max(id) AS id FROM clip WHERE upload_id=".$uploadId;
        $this->_db->query($sql, self::MASTER);
        if(!$newItem = $this->_db->fetchRow()) return false;

        $clipId = $newItem['id'];

        // insert into table clip_file_src
        $sql = "INSERT INTO clip_file_src SET clip_id=$clipId, file_src='".$data['file_src']."'";
        $this->_db->queryWrite($sql);
        
        // insert into table clip_encode
        $sql = "INSERT INTO encode_queue SET clip_id=$clipId, status=0";
        $this->_db->queryWrite($sql);
        return $clipId;
    }

    public function getFilenameFromUploadId($uploadId)
    {
        $uploadId = $this->_db->valueQuote($uploadId);
        $sql = "SELECT file_src FROM upload_queue WHERE id=$uploadId";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        
        return $row ? $row['file_src'] : false;
    }

    public function getVideoFromUploadId($uploadId)
    {
        $uploadId = $this->_db->valueQuote($uploadId);
        $sql = "SELECT * FROM upload_queue WHERE id=$uploadId";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();

        return $row ? $row : false;
    }

	/**
	 * display file size in human view
	 *
	 * @param INT $size
	 * @return INT
	 */
	private function _parseFileSize($size) {
		$units = array(' B', ' KB', ' MB', ' GB', ' TB');
		for ($i = 0; $size > 1024; $i++) { $size /= 1024; }
		return round($size, 2).$units[$i];
	}


	private function _parseTime($second) {
		if(!is_numeric($second)) return $second;
		$second = intval($second);

		$hour=intval($second/3600);
		if($hour < 10) $hour='0'.$hour;
		$second=$second%3600;
		$minute=intval($second/60);
		if($minute < 10) $minute='0'.$minute;
		$second=intval($second%60);
		if($second < 10) $second='0'.$second;
		return $hour.":".$minute.":".$second;
	}

	/**
	 * encode clip id
	 *
	 * @param INT $id
	 * @return STRING
	 */
	private function _idEncode($id)
	{
		$output = "";
		$code  = "_WzDhO2ReV1Fy3IgEjGpZiP0Cm9LaTu5Qs6tXnUwKdMfJo8NbScvYlq7rH4xBkA-";

		$id = intval($id);
		$quotient = $id;

		do
		{
			$id       = $quotient % 64;
			$quotient = $quotient >> 6; // divide by 64
			$output   = $code{$id}.$output;
		}
		while ($quotient>0);

		return $output;
	}

	/**
	 * make clip title_url
	 *
	 * @param STRING $input
	 * @return STRING
	 */
	private function _makeTitleUrl($string)
	{
		static $charMap = array(
                "à"=>"a","ả"=>"a","ã"=>"a","á"=>"a","ạ"=>"a","ă"=>"a","ằ"=>"a","ẳ"=>"a","ẵ"=>"a","ắ"=>"a","ặ"=>"a","â"=>"a","ầ"=>"a","ẩ"=>"a","ẫ"=>"a","ấ"=>"a","ậ"=>"a",
                "đ"=>"d",
                "è"=>"e","ẻ"=>"e","ẽ"=>"e","é"=>"e","ẹ"=>"e","ê"=>"e","ề"=>"e","ể"=>"e","ễ"=>"e","ế"=>"e","ệ"=>"e",
                "ì"=>'i',"ỉ"=>'i',"ĩ"=>'i',"í"=>'i',"ị"=>'i',
                "ò"=>'o',"ỏ"=>'o',"õ"=>"o","ó"=>"o","ọ"=>"o","ô"=>"o","ồ"=>"o","ổ"=>"o","ỗ"=>"o","ố"=>"o","ộ"=>"o","ơ"=>"o","ờ"=>"o","ở"=>"o","ỡ"=>"o","ớ"=>"o","ợ"=>"o",
                "ù"=>"u","ủ"=>"u","ũ"=>"u","ú"=>"u","ụ"=>"u","ư"=>"u","ừ"=>"u","ử"=>"u","ữ"=>"u","ứ"=>"u","ự"=>"u",
                "ỳ"=>"y","ỷ"=>"y","ỹ"=>"y","ý"=>"y","ỵ"=>"y",
                "À"=>"A","Ả"=>"A","Ã"=>"A","Á"=>"A","Ạ"=>"A","Ă"=>"A","Ằ"=>"A","Ẳ"=>"A","Ẵ"=>"A","Ắ"=>"A","Ặ"=>"A","Â"=>"A","Ầ"=>"A","Ẩ"=>"A","Ẫ"=>"A","Ấ"=>"A","Ậ"=>"A",
                "Đ"=>"D",
                "È"=>"E","Ẻ"=>"E","Ẽ"=>"E","É"=>"E","Ẹ"=>"E","Ê"=>"E","Ề"=>"E","Ể"=>"E","Ễ"=>"E","Ế"=>"E","Ệ"=>"E",
                "Ì"=>"I","Ỉ"=>"I","Ĩ"=>"I","Í"=>"I","Ị"=>"I",
                "Ò"=>"O","Ỏ"=>"O","Õ"=>"O","Ó"=>"O","Ọ"=>"O","Ô"=>"O","Ồ"=>"O","Ổ"=>"O","Ỗ"=>"O","Ố"=>"O","Ộ"=>"O","Ơ"=>"O","Ờ"=>"O","Ở"=>"O","Ỡ"=>"O","Ớ"=>"O","Ợ"=>"O",
                "Ù"=>"U","Ủ"=>"U","Ũ"=>"U","Ú"=>"U","Ụ"=>"U","Ư"=>"U","Ừ"=>"U","Ử"=>"U","Ữ"=>"U","Ứ"=>"U","Ự"=>"U",
                "Ỳ"=>"Y","Ỷ"=>"Y","Ỹ"=>"Y","Ý"=>"Y","Ỵ"=>"Y"
        );

        $string = strtr($string, $charMap);

		$string = $this->_cleanUpSpecialChars($string);
		return $string;
	}

	private function _cleanUpSpecialChars($string)
	{
        //$string = preg_replace( array("`[^a-zA-Z0-9\$_+*'()]`i","`[-]+`") , "-", $string);
        $string = preg_replace( array("`\W`i","`[-]+`") , "-", $string);
        return trim($string, '-');
	}


	/**
	 * Check the existing of remote file
	 * @param String: URL to file
	 * @return Bool : True if file is exist
	 */
	private function _urlFileExists($fileUrl)
	{
		$AgetHeaders = @get_headers($fileUrl);

		if (preg_match("|200|", $AgetHeaders[0])) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * get size of remote file
	 *
	 * @param String $fileUrl
	 * @return INT
	 */

	private function _urlFileSize($fileUrl)
	{
		$headers = @get_headers($fileUrl, 1);
	 	return intval($headers["Content-Length"]);
	}
}